<template>
  <div>
    <div v-if="!modal.show">
      <div style="padding:20px 20px 20px;background-color:white;">
        <a-form layout="inline" class="nmv-search-form-auto">
          <a-form-item label="设备编号">
            <a-input v-model="grid.queryParams.deviceNo" class="nmv-w-200" placeholder="请输入设备编号"></a-input>
          </a-form-item>
          <a-form-item label="SN号">
            <a-input v-model="grid.queryParams.snNo" class="nmv-w-200" placeholder="请输入SN号"></a-input>
          </a-form-item>
          <a-form-item label="车架号">
            <a-input v-model="grid.queryParams.vinNo" class="nmv-w-200" placeholder="请输入车架号"></a-input>
          </a-form-item>
          <a-form-item label="车牌号">
            <a-input v-model="grid.queryParams.licensePlateNo" class="nmv-w-200" placeholder="请输入车牌号"></a-input>
          </a-form-item>
          <a-form-item label="所属门店">
            <a-select placeholder="全部门店" allowClear show-search :filter-option="filterOption" class="nmv-w-200"
              v-model="grid.queryParams.storeId" @change="searchQuery">
              <a-select-option v-for="item in storeList" :key="item.id" :value="+item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="设备型号">
            <a-input-group compact style="width:320px;">

              <a-select style="width:40%" placeholder="全部品牌" allowClear @change="changeDevice"
                v-model="grid.queryParams.brandId" class="black_placeholders">
                <a-select-option v-for="(item, i) in brandOptions" :key="i" :value="item.id">{{ item.name }}
                </a-select-option>
              </a-select>
              <a-select style="width:60%" placeholder="全部型号" allowClear @change="searchQuery"
                v-model="grid.queryParams.modelId" class="black_placeholders">
                <a-select-option v-for="(item, i) in deviceOptions" :key="i" :value="item.id">{{ item.modelName }}
                </a-select-option>
              </a-select>
            </a-input-group>

          </a-form-item>

          <a-form-item label="关联状态">
            <a-select placeholder="全部" allowClear @change="searchQuery" v-model="grid.queryParams.associatedStatus"
              class="nmv-w-200 black_placeholders">
              <a-select-option value="1">已分配</a-select-option>
              <a-select-option value="2">待关联</a-select-option>
              <a-select-option value="3">已关联</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="启用状态">
            <a-select placeholder="全部" allowClear @change="searchQuery" v-model="grid.queryParams.enableStatus"
              class="nmv-w-200 black_placeholders">
              <a-select-option :value="1">已启用</a-select-option>
              <a-select-option :value="0">已停用</a-select-option>
              <a-select-option :value="2">已报废</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="关联时间">
            <a-range-picker style="width:320px;" v-model="time" format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']"
              @change="rangeTime"></a-range-picker>

          </a-form-item>
          <a-form-item label="停用编号">
            <a-input v-model="grid.queryParams.deactivateNo" class="nmv-w-200" placeholder="请输入停用编号"></a-input>
          </a-form-item>
          <a-form-item label="所属企业">
            <a-select v-model="grid.queryParams.companyId" @change="agentListGet(grid.queryParams.companyId)"
              placeholder="请选择企业" show-search :filter-option="filterOption" class="nmv-w-200">
              <a-select-option v-for="(item, i) in companiesAllListFilter" :key="i" :value="+item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="所属供应商">
            <a-select v-model="grid.queryParams.providerId" show-search :filter-option="filterOption"
              placeholder="请选择供应商" class="nmv-w-200" @change="searchQuery">
              <a-select-option v-for="(item, i) in agentList" :key="i" :value="+item.id">{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="searchQuery">查询</a-button>

            <a-button style="margin-left:12px" @click="onReset">重置</a-button>
          </a-form-item>
          <!-- <permissions type="vehicle/deviceManager/device/new">
            <a-button style="margin-bottom:20px;" type="primary" icon="plus" class="float-r" @click="onAdd">新增设备
            </a-button>

          </permissions>
          <permissions type="vehicle/deviceManager/device/import">
            <a-button style="margin-bottom:20px;margin-right: 12px;" class="float-r" ghost type="primary"
              @click="onImport">
              导入设备
            </a-button>
          </permissions>
          <permissions type="vehicle/deviceManager/device/export">
            <a-button style="margin-bottom:20px;margin-right: 12px;" class="float-r" ghost type="primary"
              @click="onExport">
              导出设备
            </a-button>
          </permissions> -->
          <permissions type="vehicle/deviceManager/device/batchManage">
            <a-dropdown class="float-r" style="margin-right:12px;">
              <a-menu slot="overlay" @click="handleMenuClick">
                <a-menu-item key="1"> <a-icon type="delete" />批量删除</a-menu-item>
                <a-menu-item key="2"> <a-icon type="play-circle" />批量启用</a-menu-item>
                <a-menu-item key="3"> <a-icon type="minus-circle" />批量停用</a-menu-item>

              </a-menu>
              <a-button style="margin-left: 8px"> 批量管理 <a-icon type="down" /> </a-button>
            </a-dropdown>

          </permissions>

        </a-form>
        <a-table :scroll="{ x: 1300 }" :loading="grid.load" :pagination="false" rowKey="id" :locale="locale"
          :columns="grid.columns" :data-source="grid.data">
          <span slot="action" slot-scope="text, record">
            <permissions type="vehicle/deviceManager/device/show">
              <a @click="onSee(record)">查看</a>
            </permissions>
            <a-divider type="vertical" />
            <permissions type="vehicle/deviceManager/device/position">
              <a @click="onSeeTrack(record)">定位轨迹</a>
            </permissions>
            <permissions type="device/deviceManager/device/status" v-if="record.brandId == 996 || record.brandId == 1043">
              <a-divider type="vertical" />
              <a @click="onDeviceStatus(record)">查询状态</a>
            </permissions>
            <a-divider v-if="record.associatedStatus == 2" type="vertical" />
            <permissions type="vehicle/deviceManager/device/delete">
              <a-popconfirm v-if="record.associatedStatus == 2" title="你确定要删除该设备型号吗?" ok-text="确定" cancel-text="取消"
                @confirm="onDelete(record)">
                <a class="nmv-danger">删除</a>
              </a-popconfirm>
            </permissions>
          </span>

        </a-table>
        <div v-show="grid.total !== 0" style="text-align:right;">
          <a-pagination show-size-changer :current="grid.queryParams.pageNum" :pageSize="grid.queryParams.pageSize"
            @change="onChange" style="margin-top:20px;" size="small" @showSizeChange="onShowSizeChange"
            :total="grid.total" :show-total="total => `共${grid.total}条 `" />
        </div>
      </div>
      <deviceManagementDialog ref="deviceManagementDialogRefs" @modelClose="modelClose" />
      <deviceAddDialog ref="deviceAddDialogRefs" />
      <OnImport ref="OnImportRefs" :title="titleData" @getList="queryReset" />
      <deleteSomeDevice @getList="refreshData" ref="deleteSomeDeviceRefs" />
      <enableSomeDevice @getList="refreshData" ref="enableSomeDeviceRefs" />
      <BlockUpSomeDevice @getList="refreshData" ref="BlockUpSomeDeviceRefs" />
      <DeviceStatusDrawer ref="deviceStatusDrawerRefs"></DeviceStatusDrawer>
    </div>
    <div v-if="modal.show">
      <devicePostion ref="devicePostionRefs" @close="modalClose" />
    </div>
  </div>
</template>

<script>
import Empty from '@/components/Empty/Empty'
import deviceManagementDialog from './Dialog/deviceManagementDialog'
import deviceAddDialog from './Dialog/deviceAddDialog'
import OnImport from '@/components/import/index'
import { brandAllGet } from '@/services/vehicleStore'
import deleteSomeDevice from './Dialog/deleteSomeDevice.vue'
import enableSomeDevice from './Dialog/enableSomeDevice.vue'
import BlockUpSomeDevice from './Dialog/BlockUpSomeDevice.vue'
import DeviceStatusDrawer from './Dialog/deviceStatusDrawer'
import { deviceManamentList, deviceList, deleteDetail } from '@/services/deviceManament'
import { downLoads } from '@/utils/util.js'
import { deviceExport } from '@/services/operating'
import {
  getAllStore,
  companiesAllList,
  agentList
} from '@/services/rider'
import permissions from '@/components/permissions'
import devicePostion from './modal/devicePostion.vue'
export default {
  components: {
    deviceManagementDialog,
    deviceAddDialog,
    OnImport,
    permissions,
    deleteSomeDevice,
    enableSomeDevice,
    BlockUpSomeDevice,
    devicePostion,
    DeviceStatusDrawer
  },
  data () {
    return {
      companiesAllListFilter: [],
      agentList: [],
      titleData: '',
      time: [],
      brandOptions: [],
      deviceOptions: [],
      locale: {
        emptyText: <Empty />
      },
      grid: {
        load: false,
        total: 0,
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        columns: [
          {
            title: '设备编号/SN号',
            dataIndex: 'deviceNo',
            key: 'deviceNo',
            width: 250,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">设备编号：</span>{record.deviceNo || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">SN号：</span>{record.snNo || '-'}</p>
              </div>
          },
          {
            title: '品牌型号',
            dataIndex: 'brandName',
            key: 'brandName',
            width: 180,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">品牌：</span>{record.brandName || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">型号：</span>{record.modelName || '-'}</p>
              </div>
          },
          {
            title: '当前所属门店',
            dataIndex: 'storeName',
            key: 'storeName',
            width: 140,
            ellipsis: true,
            customRender: (text) => text || '-'
          },
          {
            title: '启用状态',
            dataIndex: 'enableStatus',
            key: 'enableStatus',
            width: 140,
            customRender: (text, record) => text === 0
              ? <div style="display:flex;flex-direction:column;">
                <div style="display:flex;align-items:center"><span style="background:red;width:10px;height:10px;border-radius:50%;margin-right:8px" ></span> 停用</div>
                <span style="color:#999999;font-size:14px">{record.deactivateNo}</span>
              </div>
              : text === 1 ? <div style="display:flex;align-items:center"><span style="background:green;width:10px;height:10px;border-radius:50%;margin-right:8px"></span> 启用</div> : text === 2 ? <div style="display:flex;align-items:center"><span style="background:#F69709;width:10px;height:10px;border-radius:50%;margin-right:8px"></span> 已报废</div> : '-'
          },
          {
            title: '关联状态',
            dataIndex: 'associatedStatus',
            key: 'associatedStatus',
            width: 100,
            customRender: text =>
              +text === 1 ? (
                <a-tag class="color_orange">
                  已分配
                </a-tag>
              ) : +text === 2 ? (
                <a-tag class="color_lightBlue">
                  待关联
                </a-tag>
              ) : +text === 3 ? (
                <a-tag class="color_green">
                  已关联
                </a-tag>
              ) : ''
          },
          {
            title: '关联信息',
            dataIndex: 'vinNo',
            key: 'vinNo',
            width: 240,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">车牌号：</span>{record.licensePlateNo || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">车架号：</span>{record.vinNo || '-'}</p>
              </div>
          },
          {
            title: '所属企业/供应商',
            dataIndex: 'company',
            key: 'company',
            width: 160,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;">{record.companyName || '-'}</p>
                <p style="font-size:12px;margin:0;color:#999999">{record.providerName || '-'}</p>
              </div>
          },
          {
            title: '设备状态时间',
            dataIndex: 'associatedTime',
            key: 'associatedTime',
            width: 260,
            customRender: (text, record) =>
              <div style="display:flex;flex-direction:column;">
                <p style="font-size:14px;margin-bottom:5px;"><span style="color:#999999">添加时间：</span>{record.createTime || '-'}</p>
                <p style="font-size:14px;margin:0"><span style="color:#999999">关联时间：</span>{record.associatedTime || '-'}</p>
              </div>
          }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            fixed: 'right',
            width: 150,
            scopedSlots: { customRender: 'action' }
          }
        ],
        data: []
      },
      modal: {
        show: false
      },
      storeList: []
    }
  },
  created () {
    this.brandAllGet()
    this.getDeviceManamentList()
    this.parentCompanyIdGet()
    this.getCompaniesAllList()
  },
  methods: {
    // 查询状态
    onDeviceStatus (record) {
      this.$refs.deviceStatusDrawerRefs.open(record)
    },
    onSeeTrack (record) {
      this.modal.show = true
      // console.log(this.$refs.devicePostionRefs)
      this.$nextTick(() => {
        this.$refs.devicePostionRefs.open(record)
      })
    },
    modalClose () {
      this.modal.show = false
    },
    async getCompaniesAllList () {
      const res = await companiesAllList()
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.companiesAllListFilter = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    async agentListGet (id) {
      const res = await agentList(id)
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.agentList = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    // 刷新数据
    refreshData () {
      this.searchQuery()
    },
    // 导出
    async onExport () {
      const res = await deviceExport(this.grid.queryParams)
      downLoads('设备列表.xlsx', res)
    },
    // 批量操作
    handleMenuClick (e) {
      if (e.key === '1') {
        this.$refs.deleteSomeDeviceRefs.open()
      } else if (e.key === '2') {
        this.$refs.BlockUpSomeDeviceRefs.open()
      } else if (e.key === '3') {
        this.$refs.enableSomeDeviceRefs.open()
      }
    },
    changeDevice (values) {
      this.getAllDeviceList(values)
    },
    queryReset () {
      this.searchQuery()
    },
    modelClose () {
      this.searchQuery()
    },
    async onDelete (record) {
      const res = await deleteDetail(record.id)
      if (res.isSuccess) {
        this.$message.newFun('设备删除成功!', 'success', 2)
        this.searchQuery()
      } else {
        this.$message.newFun(res.msg, 'error', 2)
      }
    },
    onSee (row) {
      this.$refs.deviceManagementDialogRefs.onInitial(row)
    },
    onAdd () {
      this.$refs.deviceAddDialogRefs.onInitial()
    },
    onImport () {
      this.titleData = '导入设备'
      this.$refs.OnImportRefs.onInitial(6)
    },
    onChange (page, pageSize) {
      this.grid.queryParams.pageNum = page
      console.log(pageSize)
      this.searchQuery()
    },
    onShowSizeChange (current, pageSize) {
      this.grid.queryParams.pageSize = pageSize
      this.grid.queryParams.pageNum = 1
      console.log(current)
      this.searchQuery()
    },
    async getDeviceManamentList () {
      this.grid.load = true
      const res = await deviceManamentList(this.grid.queryParams)
      // console.log(res)
      if (res.code === 200) {
        // if (res.data.records.length > 0) {
        this.grid.data = res.data.records
        this.grid.total = res.data.total
        this.grid.load = false
        // } else {
        // this.$message.newFun('未查询到相关数据', 'error', 3)
        // this.grid.load = false
        // }
      } else {
        this.grid.load = false
      }
    },
    async brandAllGet () {
      const res = await brandAllGet({ type: 4 })
      const { isSuccess, data: response, msg } = res
      if (isSuccess) {
        this.brandOptions = response
      } else {
        this.$message.newFun(msg, 'error', 2)
      }
    },
    async getAllDeviceList (brandId) {
      const res = await deviceList({ brandId, status: 1 })
      if (res.isSuccess) {
        this.deviceOptions = res.data
      } else {
        this.$message.newFun(res.msg, 'error', 2)
      }
    },
    rangeTime (value) {
      if (value.length > 0) {
        const [start, end] = value
        this.grid.queryParams.associatedTimeStart = start.format('YYYY-MM-DD')
        this.grid.queryParams.associatedTimeEnd = end.format('YYYY-MM-DD')
      } else {
        delete this.grid.queryParams.associatedTimeStart
        delete this.grid.queryParams.associatedTimeEnd
        this.time = []
      }
      this.searchQuery()
    },
    searchQuery (type) {
      if (type) {
        this.grid.queryParams.pageNum = 1
        this.grid.queryParams.pageSize = 10
      }
      this.getDeviceManamentList()
    },
    onReset () {
      this.grid.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
      this.time = []
      this.getDeviceManamentList()
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      )
    },
    parentCompanyIdGet () {
      getAllStore().then((res) => {
        const { isSuccess, data: response, msg } = res
        if (isSuccess) {
          this.storeList = response
        } else {
          this.$message.newFun(msg, 'error', 2)
        }
      }).catch((err) => {
        console.log(err)
      })
    }
  }
}
</script>

<style>
.ant-popover-inner {
  width: 230px !important;
}
</style>
